package com.study.util;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.util.HashMap;

@Service
public class DynamicDataSource extends AbstractRoutingDataSource {
	
	HashMap<Object, Object> map = new HashMap<>();
	
	@Autowired
	@Qualifier("ds1")
	DataSource dataSourceMU;
	
	@Autowired
	@Qualifier("ds2")
	DataSource dataSourceMT;
	
	@PostConstruct
	public void init() {
		map.put(DynamicDataSourceType.DS1, dataSourceMU);
		map.put(DynamicDataSourceType.DS2, dataSourceMT);
		this.setTargetDataSources(map);
		this.setDefaultTargetDataSource(dataSourceMU);
	}

	@Override
	protected Object determineCurrentLookupKey() {
		// TODO Auto-generated method stub
		return DynamicDataSourceHolder.getDataSource();
	}
	
	/**
	 * 返回当前的数据源
	 */
	public DataSource getCurrentDataSource() {
		return determineTargetDataSource();
	}

}
